package ocr;

/**
 * @author 识别文字，带坐标
 * @date 2022/4/12
 * @time 19:58
 */


import java.awt.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import ClientDemo.JFramePTZControl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.baidu.aip.ocr.AipOcr;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;

public class Sample {
    //设置APPID/AK/SK
    private static final String APP_ID = "25930692";
    private static final String API_KEY = "m0wiB6THuderCTWRqqmkBane";
    private static final String SECRET_KEY = "1MbC4dnISXdAqEuoqPSkvtRDBcGfBDzG";
    private static AipOcr aipOcr = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    public static String path = getDesktopPath() + "/图片检测";
    public static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
    public static String token = AuthService.getToken();

    //高精度（带坐标）
    public static void HeihgtSampleToMap(String pictureName, String pictureStyle, Map<String, Integer> map) {
        String dataFormat = df.format(new Date());     //yyyyMMdd
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("recognize_granularity", "big");
        try {
            // 参数为本地图片路径
            String image = path + "/" + dataFormat + "/" + pictureName + "." + pictureStyle;
            JSONObject returnData = aipOcr.accurateGeneral(image, options);
            System.out.println(returnData.toString(2));
            JSONArray words_result = returnData.getJSONArray("words_result");
            List<String> list = new ArrayList<>();
            int x1 = map.get("x1") * 2;
            int y1 = map.get("y1") * 2;
            int x2 = map.get("x2") * 2;
            int y2 = map.get("y2") * 2;
            for (int i = 0; i < words_result.length(); i++) {
                JSONObject json = (JSONObject) words_result.get(i);
                JSONObject location = (JSONObject) json.get("location");
                int x =  Integer.parseInt(location.get("left").toString());
                int y =  Integer.parseInt(location.get("top").toString());
//                if (x>= x1 && x <= x2 && y >= y1 && y <= y2){
//                    list.add(json.get("words").toString());
//                }
                if ( y >= 50 && y <= 850){  //过滤掉日期和ptz
                    list.add(json.get("words").toString());
                }
//                System.out.println(json.get("words")+"  (x = "+location.get("left")+",y = "+location.get("top")+")");
            }
            System.out.println("x1="+ x1 + ", y1="+ y1+ ", x2="+ x2 + ", y2="+ y2);
            list.add("船楼坐标：左上点：(x1=" + x1 + ", y1=" + y1 + "), 右下点：(x2=" + x2 + ", y2 =" + y2+")");
            if (JFramePTZControl.showJframFlag) {
                try {
                    showJfram(list,image);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            writeFile(path + "/" + dataFormat, pictureName, list);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //高精度无坐标
    public static void HeightSample(String pictureName, String pictureStyle) {
        String dataFormat = df.format(new Date());     //yyyyMMdd
        // 传入可选参数调用接口
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
//        options.put("detect_direction", "true");
//        options.put("detect_language", "true");
//        options.put("probability", "true");
        try {
            // 参数为本地图片路径
            String image = path + "/" + dataFormat + "/" + pictureName + "." + pictureStyle;
            // 参数为本地图片路径
            List<String> list = new ArrayList<>();
            JSONObject res = aipOcr.basicAccurateGeneral(image, options);
            System.out.println(res);
            JSONArray words_result = res.getJSONArray("words_result");
            for (int i = 0; i < words_result.length(); i++) {
                JSONObject json = (JSONObject) words_result.get(i);
                String words = (String) json.get("words");
                list.add(words);
            }
            if (JFramePTZControl.showJframFlag) {
                try {
                    showJfram(list,image);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            writeFile(path + "/" + dataFormat, pictureName, list);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //网路图片
    public static void netPicture(String pictureName, String pictureStyle) {
        String dataFormat = df.format(new Date());     //yyyyMMdd
        // 传入可选参数调用接口
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
//        options.put("detect_direction", "true");
//        options.put("detect_language", "true");
//        options.put("probability", "true");
        try {
            // 参数为本地图片路径
            String image = path + "/" + dataFormat + "/" + pictureName + "." + pictureStyle;
            // 参数为本地图片路径
            List<String> list = new ArrayList<>();
            JSONObject res = aipOcr.webImage(image, options);
            System.out.println(res);
            JSONArray words_result = res.getJSONArray("words_result");
            for (int i = 0; i < words_result.length(); i++) {
                JSONObject json = (JSONObject) words_result.get(i);
                String words = (String)json.get("words");
                list.add(words.toString());
            }
            if (JFramePTZControl.showJframFlag) {
                try {
                    showJfram(list,image);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            writeFile(path + "/" + dataFormat, pictureName, list);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }




    /**
     * 获取桌面路径
     *
     * @return
     */
    public static String getDesktopPath() {
        char c = '\\';
        String s = Character.toString(c);
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File com = fsv.getHomeDirectory();
        return com.getPath().replace(s, "/");
    }

    public static void writeFile(String path, String fileName, List<String> data) {
        try {
//            StringBuffer stringBuffer = new StringBuffer(data);
            createFile(path, fileName, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文件
     *
     * @param filePath1 要创建的文件路径
     * @param fileName  要创建的文件名
     * @param list      写入文件的内容
     * @throws IOException
     */
    public static void createFile(String filePath1, String fileName, List<String> list) throws IOException {
        String filePath = filePath1;
        File dir = new File(filePath);
        // 一、检查放置文件的文件夹路径是否存在，不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();// mkdirs创建多级目录
        }
        File checkFile = new File(filePath + "/" + fileName + ".txt");
        FileWriter writer = null;
        try {
            // 二、检查目标文件是否存在，不存在则创建
            if (!checkFile.exists()) {
                checkFile.createNewFile();// 创建目标文件
            }
            // 三、向目标文件中写入内容
            // FileWriter(File file, boolean append)，append为true时为追加模式，false或缺省则为覆盖模式
            writer = new FileWriter(checkFile, true);
            for (String s : list) {
                writer.append(s + "\n");  //每行写一个单词
            }
            writer.append(" " + "\n");    //最末尾换行
            writer.flush();
            System.out.println("写入成功！！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
        }
    }

    //利用窗口显示ocr识别结果
    public static void showJfram(List<String> list,String imager) throws IOException {
        File file = new File(imager);
        BufferedImage bufferedImage = ImageIO.read(file);
        ImageIcon imageIcon = new ImageIcon(bufferedImage);
        JFrame jFrame = new JFrame();
        jFrame.setTitle("ocr识别结果");
        FlowLayout flowLayout = new FlowLayout();
//        jFrame.setLayout(flowLayout);
        jFrame.setSize(700, 700);
        JLabel jLabel1 = new JLabel();
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list) {
            stringBuilder.append("  "+s + "  ");
        }
        jLabel1.setText(stringBuilder.toString());


        JLabel jLabel = new JLabel(imageIcon) {
            @Override
            public void paint(Graphics g) {
                Image image = imageIcon.getImage();
                g.drawImage(image, 0, 0, jFrame.getWidth(), (int)(jFrame.getHeight()* 0.8), null);
                jLabel1.setBounds(0,(int)(jFrame.getHeight()* 0.8),jFrame.getWidth(),50);

            }
        };

        jLabel.setLayout(flowLayout);
        jFrame.add(jLabel1);
        jFrame.add(jLabel);
        jFrame.setVisible(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                jFrame.dispose();
            }
        }).start();
//        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


    public static void main(String[] args) {
//        new Sample().test();
       HeightSample("10.7.82.136_01_20220524220140697","jpg");
    }

    private void test() {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
//        options.put("language_type", "CHN_ENG");
//        options.put("detect_direction", "true");
//        options.put("detect_language", "true");
//        options.put("probability", "true");


        // 参数为本地图片路径
        String image = "C:\\Users\\啊林\\Desktop\\图片检测\\20220522\\15-21-56.jpg";
        JSONObject res = aipOcr.basicAccurateGeneral(image, options);   //网络图片识别接口
        System.out.println(res.toString(2));
    }


}